package org.rc.util;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

public class RequestParamUtil {

    public static Map<String, String> regularParam2Map(String params) {
        String result = regularParam(params);
        String[] tokens = StringUtils.splitPreserveAllTokens(result, '&');
        if (ArrayUtils.isNotEmpty(tokens)) {
            Map<String, String> resultMap = new HashMap<>(tokens.length);
            String[] splits = null;
            for (String token : tokens) {
                splits = StringUtils.split(token, "=");
                if (ArrayUtils.isNotEmpty(splits) && 2 == splits.length) {
                    resultMap.put(StringUtils.trim(splits[0]), StringUtils.trim(splits[1]));
                }
            }
            return resultMap;
        }
        return new HashMap<>(0);
    }


    private static String regularParam(String params) {
        if (StringUtils.isBlank(params)) {
            return StringUtils.EMPTY;
        }
        String result = StringUtils.EMPTY;
        try {
            result = StringUtils.trim(URLDecoder.decode(params, StandardCharsets.UTF_8.displayName()));
        } catch (Throwable e) {
        }

        result = StringUtils.replacePattern(result, "[&]{2,}", "&");
        result = StringUtils.replacePattern(result, "[=]{2,}", "=");
        return result;
    }
}
